package com.jt9003.controller;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.jt9003.pojo.WarehouseExcel;
import com.jt9003.service.WarehouseExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/WarehouseExcel")
public class warehouseExcelController {

    @Resource
    WarehouseExcelService warehouseExcelService;

    @RequestMapping("/write")
    @ResponseBody
    public void WarehouseExcel(HttpServletRequest request, HttpServletResponse response) {

        OutputStream osOut =null;
        ExcelWriter writer =null;
        try {
           List<WarehouseExcel> list= warehouseExcelService.exportWar();
            if (list != null) {
                response.reset();
                response.setContentType("application/vnd.ms-excel;charset=utf-8"); // 表明是excel类型
                String fileName ="warehouse" + System.currentTimeMillis() + ".xlsx";
                response.setHeader("Content-Disposition", "attachment;filename="+fileName);
                Sheet sheet = new Sheet(1, 0, WarehouseExcel.class);
                sheet.setAutoWidth(Boolean.TRUE);//设置自适应宽度
                sheet.setSheetName("入库单据表");
                //如果需要保存到ftp服务器--
                osOut = response.getOutputStream();
                writer = EasyExcelFactory.getWriter(osOut, ExcelTypeEnum.XLSX, true);
                writer.write(list, sheet);
                osOut.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.error("excel文件导出失败, 失败原因：{}", e);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("excel文件导出失败, 失败原因：{}", e);
        } finally {
            try {
                if(writer != null){
                    writer.finish();
                }
                if (osOut!=null){
                    osOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                log.error("excel文件导出失败, 失败原因：", e);
            }
        }










    }
}